package com.yangjun.utils.export;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.yangjun.utils.DvUtils;

import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


/**
 * 类导出到EXCEL
 * 
 * @author liangrui
 * 
 * @param <T>
 */
public class ExportExcel<T> {
	public void fillExcel(WritableWorkbook workbook, Class clazz,
			String[] titles, String[] fields, String sheetTitle,
			List<T> objs) throws RowsExceededException, WriteException,
			IllegalArgumentException, IllegalAccessException,
			InstantiationException, SQLException, InvocationTargetException {
		jxl.write.Label label = null;
		jxl.write.Number number = null;
		int curRow = 0, curCol = 0;
		WritableSheet sheet = workbook.createSheet(sheetTitle, 0);
		// 表头
		for (String title : titles) {
			label = new jxl.write.Label(curCol, curRow, title);
			sheet.addCell(label);
			++curCol;
		}
		// 获取数据
		List<Method> ms = DvUtils.getStringToMethodList(clazz, Arrays.asList(fields), "get","");
		// 填充数据
		for (T obj : objs) {
			++curRow;
			curCol = 0;
			for (Method m : ms) {
				
				 Object value = m.invoke(obj);
				 if (value instanceof Integer) {
	                int intValue = (Integer) value;
	                number = new jxl.write.Number(curCol, curRow, intValue);
					sheet.addCell(number);
	              } else if (value instanceof Float) {
	                float floatValue = (Float) value;
	                number = new jxl.write.Number(curCol, curRow, floatValue);
					sheet.addCell(number);
	              } else{
	            	  String strValue = String.valueOf(value);
	            	  label = new jxl.write.Label(curCol, curRow, strValue);
					  sheet.addCell(label);
	              }
//				tempStr = (String) m.invoke(obj);
//				if (DvUtils.isNumber(tempStr)) {
//					try {
//						double d = Double.parseDouble(tempStr);
//						number = new jxl.write.Number(curCol, curRow, d);
//						sheet.addCell(number);
//					} catch (java.lang.NumberFormatException e) {
//						System.out.println("Excel导出：数字转化异常，采用字符串导出。。。");
//						label = new jxl.write.Label(curCol, curRow, tempStr);
//						sheet.addCell(label);
//					}
//				} else {
//					label = new jxl.write.Label(curCol, curRow, tempStr);
//					sheet.addCell(label);
//				}
				++curCol;
			}
		}
	}
}